/**
 *  *2010-4-1 下午12:27:53  add 
 */
package com.base.myproject.client.busi.service.gcode;

import java.util.ArrayList;
import java.util.List;

import com.base.myproject.client.busi.BaseStore;
import com.base.myproject.client.busi.BaseStoreEvent;
import com.base.myproject.client.busi.BaseStoreListener;
import com.base.myproject.client.busi.BO.BusiObject;
import com.base.myproject.client.jdbc.StoreInfo;
import com.base.myproject.client.system.BaseResource;
import com.base.myproject.client.system.Env;
import com.base.myproject.client.tools.Tools;
import com.base.myproject.client.ui.BaseFormPanel;
import com.base.myproject.client.ui.BaseGrid;
import com.base.myproject.client.ui.BaseGridView;
import com.base.myproject.client.ui.BaseJDBCPanel;
import com.base.myproject.client.ui.BaseSerchHtml;
import com.base.myproject.client.ui.SWFFileUpload;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.LayoutRegion;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.Style.VerticalAlignment;
import com.extjs.gxt.ui.client.data.ModelType;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.util.Margins;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.ListView;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.VerticalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.NumberField;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.grid.CheckBoxSelectionModel;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.RowNumberer;
import com.extjs.gxt.ui.client.widget.layout.BorderLayoutData;
import com.extjs.gxt.ui.client.widget.layout.TableData;
import com.extjs.gxt.ui.client.widget.layout.TableLayout;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.user.client.ui.AbstractImagePrototype;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author Administrator 2010-4-1 javazgw@gmail.com
 */
public class GcodeManagerPanel extends BaseJDBCPanel implements
		BaseStoreListener {

	BaseStore<BusiObject> store = null;
	Button addimage = new Button("添加图片");
	Button addrecord = new Button("添加新商品");
	
	Button delimage = new Button("删除选中图片");
	Button save = new Button("保存");
	ListView<BusiObject> view=null;
	ModelType type ;
	public GcodeManagerPanel() {
		super();
		init();
	}
	public void complete()
	{
		super.complete();
		StoreFilterField<BusiObject> field = new StoreFilterField<BusiObject>() {
			@Override
			protected boolean doSelect(Store<BusiObject> store,
					BusiObject parent, BusiObject record, String property,
					String filter) {
				for (int i = 0; i < type.getFieldCount(); i++) {

					Object name = record.get(type.getField(i).getName());
					
					//TODO
					if (name!=null&&name.toString().toLowerCase().indexOf(filter.toLowerCase()) != -1) {
						return true;
					}
				}
				return false;
			}

			@Override
			protected void onFilter() {
				super.onFilter();

				// grid.getSelectionModel().select(0);
			}

		};
//		ttiratify.setText("提交确认");
		field.setAutoWidth(true);
		field.setToolTip("对当前页面进行查找");
		field.bind(store);
		field.setFieldLabel("当页搜索");
		getToolbarll().add(field);
	}
	public void init() {

		addimage.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.add_16()));
		addrecord.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.addrecord()));
		delimage.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.deleterecord()));
		save.setIcon(AbstractImagePrototype.create(BaseResource.INSTANCE.save()));
		addimage.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				// TODO Auto-generated method stub
//				BaseFileUploadDialog.getInstance().show();
				if(store.getValue("icode")==null)
				{
					MessageBox.alert("错误", "请先选择商品（商品行必须是被选中状态）", null);
				}
//				BaseFileUploadDialog bud = new BaseFileUploadDialog("b2cgcodeimage","upicode,",store.getValue("icode").toString()+","){
//					public void post()
//					{
//						//ok按钮按下的时候，刷新view
////						info
////						.setSql("select icode,b2cgcode,upicode,imagepath from b2cgcodeimage where upicode='{icode}'");
///**
// *子表不支持单独刷新，采用手动替换的办法。 
// */
//						String sql = getStoreg().getStoreinfo().getSql();
//						getStoreg().getStoreinfo().setSql("select icode,b2cgcode,upicode,imagepath from b2cgcodeimage where upicode='"+getStore().getValue("icode")+"'");
//						
//						getStoreg().reload();
//						getStoreg().getStoreinfo().setSql(sql);
//						view.refresh();
//					}
//				};
//				bud.show();
				
				SWFFileUpload swfu = new SWFFileUpload();
				swfu
						.setParams("&uploadcommand=needsave&tableinftablename=b2cgcodeimage&imagepath=imagepath&columns=upicode,&values='"+store.getValue("icode").toString()+"',");
				swfu.showDialog();
//				
			}
			
		});
		delimage.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				
				
				//System.out.println(getStoreg().getValue("upicode"));
				if(view.getSelectionModel().getSelectedItems().size()>0)
				{
					 MessageBox.confirm("确认", "确定要删除这个商品的图片吗?", new Listener<MessageBoxEvent>()
							 {

								@Override
								public void handleEvent(MessageBoxEvent be) {
									System.out.println(be.isCancelled());
									//be.
									//if(be.getButtonClicked().getText().equals(Dialog.YES))
									if(!be.isCancelled())
									{
										for(BusiObject bo:view.getSelectionModel().getSelectedItems())
										{
											System.out.println(bo.get("icode"));
											getStoreg().remove(bo);
										}
										getStoreg().trySave();
										view.refresh();
									}
									
								}
						 
							 });  
				}
				else
				{
					MessageBox.info("提示", "你还没选中商品", null);
				}
				
			}
			
		});
		addrecord.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				
				getStore().addX();
				
			}
			
		});
		save.addSelectionListener(new SelectionListener<ButtonEvent>(){

			@Override
			public void componentSelected(ButtonEvent ce) {
				
				getStore().trySave();
			}
			
		});
		
		
		this.setAutoHeight(true);
		this.setAutoWidth(true);
		
		BorderLayoutData centerData = new BorderLayoutData(LayoutRegion.CENTER);
		centerData.setMargins(new Margins(5, 5, 0, 0));
		this.add(initWeigetx(), centerData);
		registerMainStore(store);
		registerStore(store);
		this.setBusino(busi);
		setdefault();
		store.addBaseStoreListener(BaseStoreEvent.EventType.ROW_CHANGED, this);

	}

	private void setdefault() {

		store.addDefault("bcode", Env.getEnvbcode());

		store.addDefault("busicode", busi);

	}

	public Widget initWeigetx() {

		TabPanel tabpanel = new TabPanel();

//		tabpanel.setWidth(450);
//		tabpanel.setHeight(450);
		tabpanel.setAutoHeight(true);
		TabItem normal = new TabItem("产品信息");
		
		final TabItem searchframe = new TabItem("查询相关信息");
		   searchframe.setAutoHeight(true);
		   final BaseSerchHtml bsh = new BaseSerchHtml(1);
		  final Frame f1 = bsh.getSearchFrame();
		  
		   searchframe.add(f1);
		   searchframe.addListener(Events.Select, new Listener(){

			@Override
			public void handleEvent(BaseEvent be) {
				 f1.setHeight(searchframe.getHeight()+"px");
				bsh.SearchHtml(store.getValue("modeltype")==null?"":store.getValue("modeltype").toString().trim());
			
			}});
		   
			
			final TabItem searchframe2 = new TabItem("查询相关信息2");
			   searchframe2.setAutoHeight(true);
			   final BaseSerchHtml bsh2 = new BaseSerchHtml(3);
			  final Frame f = bsh2.getSearchFrame();
			   
			   searchframe2.add(f);
			   searchframe2.addListener(Events.Select, new Listener(){

				@Override
				public void handleEvent(BaseEvent be) {
					f.setHeight(searchframe2.getHeight()+"px");
					bsh2.SearchHtml(store.getValue("modeltype")==null?"":store.getValue("modeltype").toString().trim());
				
				}});
		
		HorizontalPanel h = new HorizontalPanel();
		VerticalPanel v = new VerticalPanel();
		h.add(createGrid());
		h.add(createForm());
		v.add(h);
		v.add(CreateView());
		
		normal.add(v);
		tabpanel.add(normal);
		tabpanel.add(searchframe);
		tabpanel.add(searchframe2);
		Tools.setResize(f1, 0.95, 0.95);
		Tools.setResize(f, 0.95, 0.95);

		return tabpanel;
	}

	BaseStore<BusiObject> getStore() {
		if (store == null) {
			createStore();
		}
		return store;
	}

	BaseStore<BusiObject> createStore() {
		 type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("b2cgcode");
		type.getField("b2cgcode").setType(String.class);
		type.addField("b2cgname");
		type.getField("b2cgname").setType(String.class);
		type.addField("gcode");
		type.getField("gcode").setType(String.class);
		type.addField("modeltype");
		type.getField("modeltype").setType(String.class);
		type.addField("descript");
		type.getField("descript").setType(String.class);
		type.addField("saleprice");
		type.getField("saleprice").setType(Double.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("b2cgcode");
		info.setKeyname(new String[] { "icode" });
		info.setForcenolimit("true");
		info
				.setSql("select icode,b2cgcode,b2cgname,gcode,modeltype,descript,saleprice from b2cgcode");
		// info.setParent(mainstore);// 关联主表
		// info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		// info.setLinkparent_chile_columns(new String[] { "upicode" });//
		// 关联主表字段
		store = new BaseStore<BusiObject>(type, info);
		return store;
	}

	BaseGrid grid = null;

	BaseGrid createGrid() {
		CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
		List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
		
		RowNumberer r = new RowNumberer(); 
		columns.add(r);
		columns.add(cbs.getColumn());

//		ColumnConfig C1 = new ColumnConfig("icode", "icode", 80);
//		columns.add(C1);
		
		ColumnConfig C2 = new ColumnConfig("b2cgcode", "编码", 80);
		columns.add(C2);
		ColumnConfig C3 = new ColumnConfig("b2cgname", "名称", 80);
		columns.add(C3);
		ColumnConfig C4 = new ColumnConfig("gcode", "类型", 80);
		columns.add(C4);
		ColumnConfig C5 = new ColumnConfig("modeltype", "规格", 80);
		columns.add(C5);
		ColumnConfig C6 = new ColumnConfig("descript", "描述", 80);
		columns.add(C6);
		ColumnConfig C7 = new ColumnConfig("saleprice", "销售价格", 80);
		columns.add(C7);

		ColumnModel cm = new ColumnModel(columns);
		
		grid = new BaseGrid(getStore(), cm);
		cbs.setSelectionMode(SelectionMode.SINGLE);
		grid.setSelectionModel(cbs);
		grid.setHeight(335);
		grid.setWidth(530);
		return grid;
	}

	BaseFormPanel form = null;

	BaseFormPanel createForm() {
		BaseFormPanel form = new BaseFormPanel(getStore());
		TableLayout tl = new TableLayout(2);

		TableData td = new TableData();
		td.setRowspan(1);
		td.setHorizontalAlign(HorizontalAlignment.LEFT);
		td.setVerticalAlign(VerticalAlignment.TOP);
		td.setPadding(1);
		form.setLayout(tl);
		form.setHeaderVisible(false);

//		form.add(new Label("icode:"), td);
//		NumberField C_num1 = new NumberField();
//		C_num1.setPropertyEditorType(Long.class);
//		C_num1.setName("icode");
//		form.add(C_num1, td);
		form.add(new Label("编码:"), td);
		TextField<String> C_num2 = new TextField<String>();
		C_num2.setName("b2cgcode");
		form.add(C_num2, td);
		form.add(new Label("名称:"), td);
		TextField<String> C_num3 = new TextField<String>();
		C_num3.setName("b2cgname");
		form.add(C_num3, td);
		form.add(new Label("类型:"), td);
		TextField<String> C_num4 = new TextField<String>();
		C_num4.setName("gcode");
		form.add(C_num4, td);
		form.add(new Label("规格:"), td);
		TextField<String> C_num5 = new TextField<String>();
		C_num5.setName("modeltype");
		form.add(C_num5, td);
		form.add(new Label("描述:"), td);
		TextArea C_num6 = new TextArea();
		C_num6.setName("descript");
		form.add(C_num6, td);
		form.add(new Label("销售价格:"), td);
		NumberField C_num7 = new NumberField();
		C_num7.setPropertyEditorType(Double.class);
		C_num7.setName("saleprice");
		form.add(C_num7, td);
		
		
		
		form.add(addrecord,td);
		form.add(addimage,td);
		form.add(save,td);
		
		C_num2.setWidth(200);
		C_num3.setWidth(200);
		C_num4.setWidth(200);
		C_num5.setWidth(200);
		C_num6.setWidth(200);
		C_num7.setWidth(200);
		C_num6.setHeight(145);
		C_num2.setAllowBlank(false);
		C_num3.setAllowBlank(false);
		C_num4.setAllowBlank(false);
		C_num5.setAllowBlank(false);
		C_num6.setAllowBlank(false);
		C_num7.setAllowBlank(false);
		C_num6.setMaxLength(500);
		C_num6.setPreventScrollbars(false);  
		form.inited();
		return form;
	};

	BaseStore<BusiObject> storeg = null;

	BaseStore<BusiObject> getStoreg() {
		if (storeg == null) {
			createStoreg();
		}
		return storeg;
	}

	BaseStore<BusiObject> createStoreg() {
		ModelType type = new ModelType();
		type.setRoot("records");
		type.setRecordName("record");
		type.setTotalName("totle");
		type.addField("icode");
		type.getField("icode").setType(Long.class);
		type.addField("b2cgcode");
		type.getField("b2cgcode").setType(String.class);
		type.addField("upicode");
		type.getField("upicode").setType(Long.class);
		type.addField("imagepath");
		type.getField("imagepath").setType(String.class);
		StoreInfo info = new StoreInfo();
		info.setTablename("b2cgcodeimage");
		info.setKeyname(new String[] { "icode" });
		info
				.setSql("select icode,b2cgcode,upicode,imagepath from b2cgcodeimage where upicode='{icode}'");
		info.setParent(store);// 关联主表
		info.setLinkparentcolumns(new String[] { "icode" }); // 关联主表字段
		info.setLinkparent_chile_columns(new String[] { "upicode" });// 关联主表字段
		storeg = new BaseStore<BusiObject>(type, info);
		return storeg;
	}
	BaseGrid gridg=null;
	BaseGrid createGridg(){
	CheckBoxSelectionModel cbs = new CheckBoxSelectionModel();
	List<ColumnConfig> columns = new ArrayList<ColumnConfig>();
	columns.add(cbs.getColumn());

	ColumnConfig C1 = new ColumnConfig("icode", "icode", 80);
	columns.add(C1);
	ColumnConfig C2 = new ColumnConfig("b2cgcode", "b2cgcode", 80);
	columns.add(C2);
	ColumnConfig C3 = new ColumnConfig("upicode", "upicode", 80);
	columns.add(C3);
	ColumnConfig C4 = new ColumnConfig("imagepath", "imagepath", 80);
	columns.add(C4);

	ColumnModel cm = new ColumnModel(columns);
	gridg = new BaseGrid(getStoreg(), cm);
	cbs.setSelectionMode(SelectionMode.SINGLE);
	gridg.setSelectionModel(cbs);
	return gridg ;}
	ContentPanel CreateView() {
		final ContentPanel panel = new ContentPanel();
		//panel.setCollapsible(true);
		//panel.setAnimCollapse(false);
		panel.setFrame(true);
		panel.setId("images-view");
		panel.setHeading("产品图片 (0 个产品被选中)");
		//panel.setWidth(535);

		// panel.setAutoHeight(true);
		panel.setHeight(300);
		panel.setBodyBorder(false);
		
		
		ToolBar tb= new ToolBar();
		tb.add(delimage);
		panel.setTopComponent(tb);

		view = new ListView<BusiObject>() {
			@Override
			protected BusiObject prepareData(BusiObject model) {
			//	String s = model.get("b2cgcode");
				//model.set("shortName", Format.ellipse(s, 15));
		
				return model;
			}
			
		};
		view.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);  
		view.setTemplate(getTemplate());
		view.setStore(getStoreg());
		view.setHeight(135);
		view.setItemSelector("div.thumb-wrap");
		view.getSelectionModel().addListener(Events.SelectionChange,
				new Listener<SelectionChangedEvent<BusiObject>>() {

					public void handleEvent(SelectionChangedEvent<BusiObject> be) {
						panel
								.setHeading("产品图片("
										+ be.getSelection().size()
										+ " 个产品被选中)");
					
					}

				});

		panel.add(view);
		return panel;
	}
//	return ['<tpl for=".">', 
//			'<div class="thumb-wrap" id="{}" style="border: 1px solid white">', 
//			'<div class="thumb"><img src="{imagepath}" width="128" height="128" title="{b2cgcode}"/></div>', 
//			'<span class="x-editable">{b2cgcode}</span></div>', 
//			'</tpl>', 
//			'<div class="x-clear"></div>'].join("");
	private native String getTemplate() /*-{

		
		return ['<tpl  for=".">', 
	    '<div class="thumb-wrap" id="{name}" style="border: 1px solid white;float:left;">', 
	    '<div class="thumb" style="float:left" ><img style="width:100px;height:100px;border:5px double #eee;margin: 3px 2px 2px 3px" src="{imagepath}" title="{name}"></div>', 
	    '</div>', 
	    '</tpl>',
	    '<div class="x-clear"></div>'].join(""); 
	}-*/;

	@Override
	public void BaseStoreEventHandle(BaseStoreEvent evt) {
		// TODO Auto-generated method stub

	}
}
